package com.winit.openapi.apiadapter.controller.builder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.erp.spi.product.ProductService;
import com.winit.erp.spi.product.command.QueryProductCommand;
import com.winit.erp.spi.product.vo.Product;
import com.winit.ims.spi.inventory.command.PageInventorySize4OpenApiCommand;
import com.winit.ims.spi.inventory.command.PageOverseaInventoriesCommand;
import com.winit.ims.spi.inventory.command.pageInventoryDetailCommand;
import com.winit.ims.spi.inventory.vo.PageInventoryDetailVo;
import com.winit.ims.spi.inventory.vo.PageOverseaInventoryVo;
import com.winit.ims.spi.inventory.vo.PageQueryInventorySizeVo;
import com.winit.ims.spi.vo.PageVo;
import com.winit.mms.spi.v2.command.IdCommand;
import com.winit.mms.spi.v2.item.ItemService;
import com.winit.mms.spi.v2.item.command.QueryItemCommand;
import com.winit.mms.spi.v2.item.vo.ItemVo;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;
import com.winit.ups.spi.command.CodeCommand;
import com.winit.ups.spi.warehouse.WarehouseService;
import com.winit.ups.spi.warehouse.command.QueryWarhouseByIdCommand;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

@Service("warehouseInventoryBuilder")
public class WarehouseInventoryBuilder {

    @Resource
    private WarehouseService   upsWarehouseService;

    @Resource
    private ProductService     erpProductService;

    /**
     * ums客户信息
     */
    @Resource
    private UmsCustomerService umsCustomerService;

    @Resource
    private ItemService        itemService;

    /**
     * 构建查询海外仓总库存接口入参command对象
     * 
     * @param json
     * @param platform
     */
    public PageInventorySize4OpenApiCommand buildQueryWarehouseStorageCommand(JSONObject json, String platform) {

        PageInventorySize4OpenApiCommand command = new PageInventorySize4OpenApiCommand();
        command.setCtx(CommandContext.getContext());
        command.setCustomerCode(getCustomerCode());
        command.setPlatform(platform);

        WarehouseVo warehouseVo = queryWarehouseByIdOrCode(json);
        if (warehouseVo != null) {
            command.setWarehouseCode(warehouseVo.getCode());
        }

        if (json.containsKey("isActive")) {
            String isActive = json.getString("isActive");
            command.setIsActive(isActive);
        }
        // 构建分页参数
        PageVo pageVo = new PageVo();
        if (json.containsKey("pageNum") && json.containsKey("pageSize")) {
            pageVo.setPageNo(json.getIntValue("pageNum"));
            pageVo.setPageSize(json.getIntValue("pageSize"));
        } else {
            pageVo.setPageNo(ApiConstant.PAGE_NO_DEFAULT);
            pageVo.setPageSize(ApiConstant.PAGE_SIZE_DEFAULT);
        }

        command.setPageVo(pageVo);

        return command;

    }

    private WarehouseVo queryWarehouseByIdOrCode(JSONObject json) {
        WarehouseVo warehouseVo = null;
        String warehouseIdStr = json.getString("warehouseID");
        String warehouseCode = json.getString("warehouseCode");
        if (json.containsKey("warehouseID") && StringUtils.isNotBlank(json.getString("warehouseID"))) {
            Long warehouseId = json.getLongValue("warehouseID");
            QueryWarhouseByIdCommand houseCommand = new QueryWarhouseByIdCommand();
            houseCommand.setWarehouseId(Long.valueOf(warehouseId));
            warehouseVo = upsWarehouseService.queryWarehouseById(houseCommand);

            if (warehouseVo != null && StringUtils.isNotBlank(json.getString("warehouseCode"))) {
                if (!warehouseVo.getCode().equalsIgnoreCase(warehouseCode)) {
                    throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_ID_AND_CODE_NOT_MATCH,
                        warehouseIdStr,
                        warehouseCode);
                }
            }

        }

        if (json.containsKey("warehouseCode") && StringUtils.isNotBlank(json.getString("warehouseCode"))) {
            CodeCommand codeCommand = new CodeCommand();
            codeCommand.setCode(warehouseCode);
            codeCommand.setCustomerCode(getCustomerCode());
            warehouseVo = upsWarehouseService.queryWarehouseByCode(codeCommand);

            if (warehouseVo != null && StringUtils.isNotBlank(json.getString("warehouseID"))) {
                if (!warehouseVo.getWarehouseId().toString().equalsIgnoreCase(warehouseIdStr)) {
                    throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_ID_AND_CODE_NOT_MATCH,
                        warehouseIdStr,
                        warehouseCode);
                }
            }
        }

        if (null == warehouseVo) {
            throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS,
                StringUtils.isNotBlank(warehouseIdStr) ? warehouseIdStr : warehouseCode);
        }

        return warehouseVo;
    }

    /**
     * 构建查询海外仓产品库存列表接口入参command对象
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    public PageOverseaInventoriesCommand buildProductInventoryListCommand(JSONObject json) {

        PageOverseaInventoriesCommand command = new PageOverseaInventoriesCommand();
        command.setCtx(CommandContext.getContext());
        command.setCustomerCode(getCustomerCode());

        PageVo pageVo = new PageVo();

        if (json.containsKey("pageNum") && json.containsKey("pageSize")) {
            pageVo.setPageNo(json.getIntValue("pageNum"));
            pageVo.setPageSize(json.getIntValue("pageSize"));
        } else {
            pageVo.setPageNo(ApiConstant.PAGE_NO_DEFAULT);
            pageVo.setPageSize(ApiConstant.PAGE_SIZE_DEFAULT);
        }
        // 排序字段
        if (json.containsKey("sort") && json.containsKey("sortColumn")) {
            pageVo.setFieldName(json.getString("sortColumn"));
        }
        command.setPageVo(pageVo);

        if (json.containsKey("source")) {
            command.setSource(json.getString("source"));// 是否卖家网站
        }

        if (json.containsKey("isActive")) {
            command.setIsActive(json.getString("isActive"));// 是否有效
        }

        if (json.containsKey("isprohibitoutbound")) {
            command.setIsProhibitOutbound(json.getString("isprohibitoutbound"));// 是否禁止出库
        }

        if (json.containsKey("productCode") && StringUtils.isNotBlank(json.getString("productCode"))) {
            ItemVo item = null;
            QueryItemCommand queryItemCommand = new QueryItemCommand();
            queryItemCommand.setCtx(CommandContext.getContext());
            queryItemCommand.setCustomerCode(getCustomerCode());
            String productCode = json.getString("productCode").trim();
            queryItemCommand.setSkuCode(productCode);
            // 校验productCode合法性
            if (json.containsKey("specification") && StringUtils.isNotBlank(json.getString("specification"))) {
                String specification = json.getString("specification").trim();
                queryItemCommand.setSpecification(specification);
                item = itemService.queryItemBySkuAndCustomerCode(queryItemCommand);
                if (item == null) {
                    throw new ApiException(ErrorCode.ITEM_NOT_EXIST, productCode);
                }

            } else {
                item = itemService.queryItemBySkuAndCustomerCode(queryItemCommand);
                if (item == null) {
                    throw new ApiException(ErrorCode.ITEM_NOT_EXIST, productCode);
                }
            }
            command.setMerchandiseCode(json.getString("productCode"));
        }

        if (json.containsKey("name") && StringUtils.isNotBlank(json.getString("name"))) {
            command.setMerchandiseName(json.getString("name"));
        }

        if (json.containsKey("warehouseId") && StringUtils.isNotBlank(json.getString("warehouseId"))) {
            command.setWarehouseCodes(buildWarehouseCodesString(json, command));
        } else if (json.containsKey("warehouseCode") && StringUtils.isNotBlank(json.getString("warehouseCode"))) {

            String codeStr = json.getString("warehouseCode");
            String[] codeArray = codeStr.split("\\,");

            String code = codeArray[0];
            CodeCommand houseCommand = new CodeCommand();
            houseCommand.setCode(code);
            WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(houseCommand);
            if (warehouseVo != null) {
                command.setCountryCode(warehouseVo.getCountryCode());
            }

            command.setWarehouseCodes(json.getString("warehouseCode"));

        }

        if (json.containsKey("DOITier") && StringUtils.isNotBlank(json.getString("DOITier"))) {
            command.setDoi(json.getString("DOITier"));
        }

        // 库存类别:Country-国家;Warehouse-仓库
        if (json.containsKey("inventoryType") && StringUtils.isNotBlank(json.getString("inventoryType"))) {
            String inventoryType = json.getString("inventoryType");
            command.setIsCountry("Country".equalsIgnoreCase(inventoryType) ? "Y" : "N");
        } else if (json.containsKey("warehouseId") && StringUtils.isNotBlank(json.getString("warehouseId"))) {
            command.setIsCountry("N");
        }

        return command;

    }

    public pageInventoryDetailCommand buildQueryProductInventoryDetailCommand(JSONObject json) {

        pageInventoryDetailCommand command = new pageInventoryDetailCommand();
        command.setCtx(CommandContext.getContext());
        String customerCode = getCustomerCode();
        command.setCustomerCode(customerCode);

        // 如果传入了SKU和规格，则优先使用SKU和规格查询
        if (json.containsKey("productCode") && StringUtils.isNotBlank(json.getString("productCode"))) {
            ItemVo item = null;
            QueryItemCommand queryItemCommand = new QueryItemCommand();
            queryItemCommand.setCtx(CommandContext.getContext());
            queryItemCommand.setCustomerCode(getCustomerCode());
            String productCode = json.getString("productCode").trim();
            queryItemCommand.setSkuCode(productCode);
            // 校验productCode合法性
            if (json.containsKey("specification") && StringUtils.isNotBlank(json.getString("specification"))) {
                String specification = json.getString("specification").trim();
                queryItemCommand.setSpecification(specification);
                item = itemService.queryItemBySkuAndCustomerCode(queryItemCommand);
                if (item == null) {
                    throw new ApiException(ErrorCode.ITEM_NOT_EXIST, productCode);
                }
                command.setSpecification(specification);
            } else {
                item = itemService.queryItemBySkuAndCustomerCode(queryItemCommand);
                if (item == null) {
                    throw new ApiException(ErrorCode.ITEM_NOT_EXIST, productCode);
                }
            }
            command.setMerchandiseCode(json.getString("productCode"));
        } else if (json.containsKey("productId")) {
            IdCommand itemCommand = new IdCommand();
            Long productId = json.getLongValue("productId");
            itemCommand.setId(json.getLongValue("productId"));
            Product product = erpProductService.getProductId(productId);
            if (product == null) {
                throw new ApiException(ErrorCode.ITEM_NOT_EXIST, String.valueOf(productId));
            }
            command.setMerchandiseCode(product.getValue());
            command.setSpecification(product.getSpecification());
        }

        if (json.containsKey("warehouseId") && StringUtils.isNotBlank(json.getString("warehouseId"))) {
            command.setWarehouseCodes(buildWarehouseCodesString(json, null));
        } else if (json.containsKey("warehouseCode") && StringUtils.isNotBlank(json.getString("warehouseCode"))) {
            command.setWarehouseCodes(json.getString("warehouseCode"));

        }

        return command;

    }

    public List<Map<String, Object>> buildQueryWarehouseStorageResult(List<PageQueryInventorySizeVo> list,
                                                                      JSONObject json) {
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

        if (CollectionUtils.isEmpty(list)) {
            return dataList;
        }
        WarehouseVo warehouseVo = queryWarehouseByIdOrCode(json);
        for (PageQueryInventorySizeVo vo : list) {
            Map<String, Object> map = new HashMap<String, Object>();// 存放每行数据
            if (warehouseVo != null) {
                map.put("warehouseCode", warehouseVo.getCode());// 仓库编码
                map.put("warehouseName", warehouseVo.getName());// 仓库名称
                map.put("warehouseID", warehouseVo.getWarehouseId());// 仓库ID

            }

            map.put("productName", StringUtils.trimToNull(vo.getMerchandiseName()));// 商品编码
            map.put("productCode", vo.getMerchandiseCode());// 商品编码
            map.put("specification", StringUtils.trimToNull(vo.getSpecification()));// 规格

            map.put("productLength",
                vo.getProductLength() == null ? 0 : vo.getProductLength().setScale(2, BigDecimal.ROUND_HALF_UP));// 长
            // 兼容老版本，老版本叫producLength
            map.put("producLenght",
                vo.getProductLength() == null ? 0 : vo.getProductLength().setScale(2, BigDecimal.ROUND_HALF_UP));// 长
            map.put("productWidth",
                vo.getProductWidth() == null ? 0 : vo.getProductWidth().setScale(2, BigDecimal.ROUND_HALF_UP));// 宽
            map.put("productHeight",
                vo.getProductHeight() == null ? 0 : vo.getProductHeight().setScale(2, BigDecimal.ROUND_HALF_UP));// 高
            map.put("productWeight",
                vo.getProductWeight() == null ? 0 : vo.getProductWeight().setScale(6, BigDecimal.ROUND_HALF_UP));// 重量

            map.put("inventory", vo.getInStockQty() == null ? "0" : String.valueOf(vo.getInStockQty()));

            map.put("qtySw", vo.getSwQty() == null ? "0" : String.valueOf(vo.getSwQty()));// 存储模式库存
            map.put("prohibitUsableQty", vo.getProhibitUsableQty() == null ? 0 : vo.getProhibitUsableQty());// 禁止出库数量

            int qtyOrdered1 = vo.getOnOrderQty() == null ? 0 : vo.getOnOrderQty();
            int qtyOrdered2 = vo.getOnOrderAllocationQty() == null ? 0 : vo.getOnOrderAllocationQty();
            int qtyOrdered3 = vo.getSwOnOrderQty() == null ? 0 : vo.getSwOnOrderQty();

            int qtyReserved1 = vo.getWaitingOutboundQty() == null ? 0 : vo.getWaitingOutboundQty();
            int qtyReserved2 = vo.getWaitingDestructionQty() == null ? 0 : vo.getWaitingDestructionQty();
            int qtyReserved3 = vo.getWaitingOutboundAllocationQty() == null ? 0 : vo.getWaitingOutboundAllocationQty();
            int qtyReserved4 = vo.getLostConfirmingQty() == null ? 0 : vo.getLostConfirmingQty();
            int qtyReserved5 = vo.getFrozenQty() == null ? 0 : vo.getFrozenQty();
            int qtyReserved6 = vo.getSwStoreQty() == null ? 0 : vo.getSwStoreQty();

            map.put("pipelineInventory", String.valueOf(qtyOrdered1 + qtyOrdered2 + qtyOrdered3));// 在途出库
            // 待出库 = 标准待发+销毁待发+调拨待发+丢失确认中+冻结
            map.put("reservedInventory",
                String.valueOf(qtyReserved1 + qtyReserved2 + qtyReserved3 + qtyReserved4 + qtyReserved5 + qtyReserved6));

            map.put("qtyShareStorage", String.valueOf(0));// 共享库存

            int qtyHisOut1 = vo.getOutboundQty() == null ? 0 : vo.getOutboundQty();
            int qtyHisOut2 = vo.getOutboundAllocationQty() == null ? 0 : vo.getOutboundAllocationQty();
            int qtyHisOut3 = vo.getDestructionQty() == null ? 0 : vo.getDestructionQty();
            map.put("qtySellHisOut", String.valueOf(qtyHisOut1 + qtyHisOut2 + qtyHisOut3));// 历史销量

            map.put("qtyAvailable", vo.getUsableQty() == null ? "0" : String.valueOf(vo.getUsableQty()));// 可用库存

            map.put("isActive", vo.getIsActive());// 是否有效

            dataList.add(map);

        }

        return dataList;

    }

    public List<Map<String, Object>> buildQueryProductInventoryDetailResult(List<PageInventoryDetailVo> list) {
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

        if (CollectionUtils.isEmpty(list)) {
            return dataList;
        }

        for (PageInventoryDetailVo vo : list) {
            Map<String, Object> map = new HashMap<String, Object>();// 存放每行数据
            CodeCommand houseCommand = new CodeCommand();
            houseCommand.setCode(vo.getWarehouseCode());
            WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(houseCommand);
            if (null != warehouseVo) {
                map.put("warehouseCode", vo.getWarehouseCode());// 仓库编码
                map.put("warehouseName", vo.getWarehouseName());// 仓库名称
                map.put("warehouseId", String.valueOf(warehouseVo.getWarehouseId()));// 仓库ID
            }

            map.put("productCode", vo.getMerchandiseCode());// 商品编码
            map.put("specification", vo.getSpecification());// 规格
            String isProhibitOutbound = vo.getIsProhibitOutbound();
            if (isProhibitOutbound.contains("Y") && isProhibitOutbound.contains("N")) {
                isProhibitOutbound = "PART";
            } else if (isProhibitOutbound.contains("Y")) {
                isProhibitOutbound = "Y";
            } else {
                isProhibitOutbound = "N";
            }
            map.put("isprohibitoutbound", isProhibitOutbound);// 禁止出库

            int qtyHisIn1 = vo.getInboundQty() == null ? 0 : vo.getInboundQty();
            int qtyHisIn2 = vo.getInboundAllocationQty() == null ? 0 : vo.getInboundAllocationQty();

            map.put("qtyHisIn", String.valueOf(qtyHisIn1 + qtyHisIn2));// 历史入库
            // if ("Y".equals(vo.getIsProhibitOutbound()) && !isOpc) {
            // map.put("qtyAvailable", 0);// 可用库存
            // } else {
            map.put("qtyAvailable", vo.getUsableQty() == null ? "0" : String.valueOf(vo.getUsableQty()));// 可用库存
            map.put("prohibitUsableQty", vo.getProhibitUsableQty() == null ? 0 : vo.getProhibitUsableQty());// 禁止出库数量
            // }

            int qtyOrdered1 = vo.getOnOrderQty() == null ? 0 : vo.getOnOrderQty();
            int qtyOrdered2 = vo.getOnOrderAllocationQty() == null ? 0 : vo.getOnOrderAllocationQty();
            int qtyOrdered3 = vo.getSwOnOrderQty() == null ? 0 : vo.getSwOnOrderQty();

            int qtyReserved1 = vo.getWaitingOutboundQty() == null ? 0 : vo.getWaitingOutboundQty();
            int qtyReserved2 = vo.getWaitingDestructionQty() == null ? 0 : vo.getWaitingDestructionQty();
            int qtyReserved3 = vo.getWaitingOutboundAllocationQty() == null ? 0 : vo.getWaitingOutboundAllocationQty();
            int qtyReserved4 = vo.getLostConfirmingQty() == null ? 0 : vo.getLostConfirmingQty();
            int qtyReserved5 = vo.getFrozenQty() == null ? 0 : vo.getFrozenQty();
            int qtyReserved6 = vo.getSwStoreQty() == null ? 0 : vo.getSwStoreQty();

            map.put("qtyOrdered", String.valueOf(qtyOrdered1 + qtyOrdered2 + qtyOrdered3));// 在途库存
            // 待出库 = 标准待出库+销毁待出库+调拨待出库+丢失确认中+冻结
            map.put("qtyReserved",
                String.valueOf(qtyReserved1 + qtyReserved2 + qtyReserved3 + qtyReserved4 + qtyReserved5 + qtyReserved6));// 待出库
            map.put("qtySw", vo.getSwQty() == null ? "0" : String.valueOf(vo.getSwQty()));// 存储模式库存
            // 出库历史销量+调拨历史销量
            int qtyHisOut1 = vo.getOutboundQty() == null ? 0 : vo.getOutboundQty();
            int qtyHisOut2 = vo.getOutboundAllocationQty() == null ? 0 : vo.getOutboundAllocationQty();
            int qtyHisOut3 = vo.getDestructionQty() == null ? 0 : vo.getDestructionQty();
            map.put("qtyHisOut", String.valueOf(qtyHisOut1 + qtyHisOut2 + qtyHisOut3));// 历史销量

            map.put("qtyShareStorage", 0);// 共享库存
            map.put("qtySellHisOut", 0);// 历史代销量
            // 退货商品维护成原SKU时
            map.put("DOI", vo.getDoi() != null ? vo.getDoi() : "");// 前日DOI
            map.put("averageSalesQty",
                (vo.getAvgSaleQty() != null && vo.getAvgSaleQty().intValue() > 0) ? vo.getAvgSaleQty() : "");// 30天内平均销量
            map.put("averageStockQty",
                vo.getAverageStockQty() != null && vo.getAverageStockQty().intValue() > 0 ? vo.getAverageStockQty() : "");// 30天内平均库存数
            map.put("avgSales", vo.getAverageStockQty() != null ? vo.getAverageStockQty() : 0);

            dataList.add(map);
        }
        return dataList;

    }

    public List<Map<String, Object>> buildQueryProductInventoryListResult(List<PageOverseaInventoryVo> list,
                                                                          JSONObject json) {
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

        if (CollectionUtils.isEmpty(list)) {
            return dataList;
        }

        StringBuffer idStrBUffer = new StringBuffer();
        StringBuffer codeStrBUffer = new StringBuffer();

        StringBuffer nameStrBUffer = new StringBuffer();

        if (json.containsKey("warehouseId") && StringUtils.isNotBlank(json.getString("warehouseId"))) {
            String idStr = json.getString("warehouseId");
            idStrBUffer.append(idStr);
            String[] idArray = idStr.split("\\,");
            for (String id : idArray) {
                QueryWarhouseByIdCommand houseCommand = new QueryWarhouseByIdCommand();
                houseCommand.setWarehouseId(Long.valueOf(id));
                WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseById(houseCommand);
                if (warehouseVo != null) {
                    codeStrBUffer.append(warehouseVo.getCode()).append(",");
                    nameStrBUffer.append(warehouseVo.getName()).append(",");
                }

            }
            if (codeStrBUffer.toString().endsWith(",")) {
                codeStrBUffer.deleteCharAt(codeStrBUffer.lastIndexOf(","));
            }

        }
        if (idStrBUffer.length() <= 3) {// 说明未传ID参数
            if (json.containsKey("warehouseCode") && StringUtils.isNotBlank(json.getString("warehouseCode"))) {

                String codeStr = json.getString("warehouseCode");
                codeStrBUffer.append(codeStr);
                String[] codeArray = codeStr.split("\\,");
                for (String code : codeArray) {
                    CodeCommand houseCommand = new CodeCommand();
                    houseCommand.setCode(code);
                    WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(houseCommand);
                    if (warehouseVo != null) {
                        idStrBUffer.append(warehouseVo.getWarehouseId()).append(",");
                        nameStrBUffer.append(warehouseVo.getName()).append(",");
                    }

                }
                if (idStrBUffer.toString().endsWith(",")) {
                    idStrBUffer.deleteCharAt(idStrBUffer.lastIndexOf(","));
                }

            }
        }

        if (nameStrBUffer.toString().endsWith(",")) {
            nameStrBUffer.deleteCharAt(nameStrBUffer.lastIndexOf(","));
        }

        for (PageOverseaInventoryVo vo : list) {
            Map<String, Object> map = new HashMap<String, Object>();// 存放每行数据
            map.put("warehouseCode", codeStrBUffer.toString());// 仓库编码
            map.put("warehouseName", nameStrBUffer.toString());// 仓库名称
            map.put("warehouseId", idStrBUffer.toString());// 仓库ID
            // 此处不应还调用ERP接口，由于MMS未迁移ERP的productId
            QueryProductCommand command = new QueryProductCommand();
            command.setCode(vo.getMerchandiseCode());
            command.setSpecification(vo.getSpecification());
            Product product = erpProductService.queryProductByKey(command);
            map.put("productId", product == null ? StringUtils.EMPTY : String.valueOf(product.getProductId()));// 产品ID
            map.put("productCode", vo.getMerchandiseCode());// 产品编码
            map.put("specification", StringUtils.trimToNull(vo.getSpecification()));// 规格
            map.put("name", vo.getMerchandiseName());// 中文名称
            map.put("eName", vo.getMerchandiseEnName());// 英文名称
            map.put("description", vo.getDescription());// 描述
            String isProhibitOutbound = vo.getIsProhibitOutbound();
            if (isProhibitOutbound.contains("Y") && isProhibitOutbound.contains("N")) {
                isProhibitOutbound = "PART";
            } else if (isProhibitOutbound.contains("Y")) {
                isProhibitOutbound = "Y";
            } else {
                isProhibitOutbound = "N";
            }

            int qtyHisIn1 = vo.getInboundQty() == null ? 0 : vo.getInboundQty();
            int qtyHisIn2 = vo.getInboundAllocationQty() == null ? 0 : vo.getInboundAllocationQty();
            map.put("isprohibitoutbound", isProhibitOutbound);// 禁止出库
            map.put("qtyHisIn", String.valueOf(qtyHisIn1 + qtyHisIn2));// 历史入库
            // if ("Y".equals(vo.getIsProhibitOutbound()) && !isOpc) {
            // map.put("qtyAvailable", 0);// 可用库存
            // } else {
            map.put("qtyAvailable", String.valueOf(vo.getUsableQty()));// 可用库存
            map.put("prohibitUsableQty", vo.getProhibitUsableQty() == null ? 0 : vo.getProhibitUsableQty());// 禁止出库数量
            // }

            int qtyOrdered1 = vo.getOnOrderQty() == null ? 0 : vo.getOnOrderQty();
            int qtyOrdered2 = vo.getOnOrderAllocationQty() == null ? 0 : vo.getOnOrderAllocationQty();
            int qtyOrdered3 = vo.getSwOnOrderQty() == null ? 0 : vo.getSwOnOrderQty();

            int qtyReserved1 = vo.getWaitingOutboundQty() == null ? 0 : vo.getWaitingOutboundQty();
            int qtyReserved2 = vo.getWaitingDestructionQty() == null ? 0 : vo.getWaitingDestructionQty();
            int qtyReserved3 = vo.getWaitingOutboundAllocationQty() == null ? 0 : vo.getWaitingOutboundAllocationQty();
            int qtyReserved4 = vo.getLostConfirmingQty() == null ? 0 : vo.getLostConfirmingQty();
            int qtyReserved5 = vo.getFrozenQty() == null ? 0 : vo.getFrozenQty();
            int qtyReserved6 = vo.getSwStoreQty() == null ? 0 : vo.getSwStoreQty();

            map.put("qtyOrdered", String.valueOf(qtyOrdered1 + qtyOrdered2 + qtyOrdered3));// 在途库存
            // 待出库 = 标准待出库+销毁待出库+调拨待出库+丢失确认中+冻结
            map.put("qtyReserved",
                String.valueOf(qtyReserved1 + qtyReserved2 + qtyReserved3 + qtyReserved4 + qtyReserved5 + qtyReserved6));// 待出库

            map.put("qtySw", String.valueOf(vo.getSwQty()));// 存储模式库存
            int qtyHisOut1 = vo.getOutboundQty() == null ? 0 : vo.getOutboundQty();
            int qtyHisOut2 = vo.getOutboundAllocationQty() == null ? 0 : vo.getOutboundAllocationQty();
            int qtyHisOut3 = vo.getDestructionQty() == null ? 0 : vo.getDestructionQty();
            map.put("qtyHisOut", String.valueOf(qtyHisOut1 + qtyHisOut2 + qtyHisOut3));// 历史销量
            map.put("qtyShareStorage", 0);// 共享库存
            map.put("qtySellHisOut", 0);// 历史代销量
            map.put("isReturn", vo.getIsReturn());// 是否为退货商品
            if ("Y".equals(vo.getIsReturn())) {
                // 退货商品维护成原SKU时
                map.put("DOI", "");// 前日DOI
                map.put("averageStockQty", "");// 30天内平均库存数
                map.put("averageSalesQty", "");// 30天内平均销量
            } else {
                map.put("DOI", null != vo.getDoi() ? vo.getDoi() : "");// 前日DOI
                map.put("DOIAll", null != vo.getCountryDoi() ? vo.getCountryDoi() : "");// 前日DOI
                map.put("averageStockQty", null != vo.getAverageStockQty() ? vo.getAverageStockQty() : "");// 30天内平均库存数
                map.put("averageStockQty7", null != vo.getAverageStockQty7() ? vo.getAverageStockQty7() : "");// 7天内平均库存数
                map.put("averageStockQty15", null != vo.getAverageStockQty15() ? vo.getAverageStockQty15() : "");// 15天内平均库存数
                map.put("averageSalesQty", null != vo.getAverageSalesQty() ? vo.getAverageSalesQty() : "");// 30天内平均销量
                map.put("averageSalesQty7", null != vo.getAverageSalesQty7() ? vo.getAverageSalesQty7() : "");// 7天内平均销量
                map.put("averageSalesQty15", null != vo.getAverageSalesQty15() ? vo.getAverageSalesQty15() : "");// 15天内平均销量
                map.put("avgSales", null != vo.getAverageStockQty() ? vo.getAverageStockQty() : 0);

            }

            dataList.add(map);
        }
        return dataList;

    }

    private String buildWarehouseCodesString(JSONObject json, PageOverseaInventoriesCommand command) {
        String warehouseIdStr = json.getString("warehouseId");
        if (StringUtils.isNotBlank(warehouseIdStr)) {
            String[] idArray = warehouseIdStr.split("\\,");
            StringBuffer codeString = new StringBuffer();
            for (int i = 0; i < idArray.length; i++) {
                String warehouseId = idArray[i];
                QueryWarhouseByIdCommand houseCommand = new QueryWarhouseByIdCommand();
                houseCommand.setWarehouseId(Long.valueOf(warehouseId));
                WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseById(houseCommand);
                if (null == warehouseVo) {
                    throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS, warehouseId);
                }
                if (json.containsKey("warehouseCode") && StringUtils.isNotBlank(json.getString("warehouseCode"))) {
                    String warehouseCode = json.getString("warehouseCode");
                    if (!warehouseCode.trim().equalsIgnoreCase(warehouseVo.getCode())) {
                        throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS, warehouseCode);
                    }
                }
                // 国家编码取第一个仓库所在的国家编码
                if (i == 0 && command != null) {
                    command.setCountryCode(warehouseVo.getCountryCode());
                }
                if (i < idArray.length - 1) {
                    codeString.append(warehouseVo.getCode()).append(",");
                } else {
                    codeString.append(warehouseVo.getCode());
                }

            }
            return codeString.toString();
        }
        return null;
    }

    private String getCustomerCode() {
        String customerCode = null;
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner != null) {
            customerCode = bpartner.getValue();
        } else {
            QueryCompanylCommand userCommand = new QueryCompanylCommand();
            userCommand.setEmail(CommandContext.getContext().getUsername());
            // 获取客户编码
            CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
            customerCode = customer.getCode();
        }
        return customerCode;
    }

}
